package main

import (
	"crypto/tls"
	"crypto/x509"
	"fmt"
	"io/ioutil"
	"net/http"
	"time"
)

var (
	caCert0    = "./gen_crypto/crypto-config/peerOrganizations/org1.demo.com/peers/peer0.org1.demo.com/tls/ca.crt"
	caCert1    = "./gen_crypto/crypto-config/peerOrganizations/org2.demo.com/peers/peer0.org2.demo.com/tls/ca.crt" // client's ca
	caCert2    = "./gen_crypto/crypto-config/peerOrganizations/org3.demo.com/peers/peer0.org3.demo.com/tls/ca.crt"
	caCert3    = "./gen_crypto/crypto-config/peerOrganizations/org4.demo.com/peers/peer0.org4.demo.com/tls/ca.crt"
	serverCert = "./gen_crypto/crypto-config/peerOrganizations/org3.demo.com/peers/peer0.org3.demo.com/tls/server.crt" // server's cert
	serverKey  = "./gen_crypto/crypto-config/peerOrganizations/org3.demo.com/peers/peer0.org3.demo.com/tls/server.key" // server's private key
)

type Server struct {
}

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()

	oid := r.FormValue("oid")
	fmt.Println()
	fmt.Println("peercertificate", (*(r.TLS)).PeerCertificates[0].Signature)

	fmt.Println(oid, "Hello World! %s", time.Now())
	a := "helloworld"
	w.Write([]byte(a))
}

func main() {
	pool := x509.NewCertPool()
	addTrust(pool, caCert0)
	addTrust(pool, caCert1)
	addTrust(pool, caCert2)
	addTrust(pool, caCert3)

	server := &http.Server{
		Addr:    ":12306",
		Handler: &Server{},
		TLSConfig: &tls.Config{
			ClientCAs:  pool,
			ClientAuth: tls.RequireAndVerifyClientCert,
		},
	}

	err := server.ListenAndServeTLS(serverCert, serverKey) //添加服务端证书和密钥
	if err != nil {
		fmt.Println("ListenAndServeTLS err:", err)
	}

	fmt.Println(pool.Subjects())
}

func addTrust(pool *x509.CertPool, path string) {
	aCrt, err := ioutil.ReadFile(path)
	if err != nil {
		fmt.Println("ReadFile err:", err)
		return
	}
	pool.AppendCertsFromPEM(aCrt)
}
